﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Microsoft.MSE.Data
{
    /// <summary>
    /// SQL Connection Factory
    /// </summary>
    public static class ConnectionFactory
    {
        /// <summary>
        /// Creates a SQL connection.
        /// </summary>
        /// <returns>SqlConnection</returns>
        public static SqlConnection CreateConnection()
        {
            return new SqlConnection();
        }

        /// <summary>
        /// Creates a SQL connection.
        /// </summary>
        /// <returns>SqlConnection</returns>
        public static SqlConnection OpenConnection(string connectionName)
        {
            string connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
            SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();
            return connection;
        }

        /// <summary>
        /// Replaced repeated functionality in DAL class.
        /// </summary>
        /// <param name="connection">SqlConnection</param>
        /// <returns>True indicates that autoclose is enabled.</returns>
        public static bool CheckConnection(SqlConnection connection)
        {
            if (connection == null)
            {
                connection = CreateConnection();
            }

            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
                return true;
            }

            return false;
        }
    }
}